<?php
// +----------------------------------------------------------------------
// | 登录验证
// +----------------------------------------------------------------------

namespace app\common\middleware;

use app\common\model\User;

class Api
{
    public function handle($request, \Closure $next)
    {
        // Authorization
        $authorization = $request->header('authorization', '');
        if (strpos($authorization, 'Bearer') === false) {
            return json(['code' => 10000, 'msg' => 'Authorization null'], 401);
        }
        $appCode = substr($authorization, 7);
        if ($request->isOptions()) {
            return json(['code' => 204, 'msg' => 'No Content'], 204);
        }
        // 验证APPCODE信息
        $user = User::where('app_secret', $appCode)->find();
        if (!$user){
            return json(['code' => 10001, 'msg' => 'Authorization failed'], 401);
        }

        // 传递数据
        $request->user = (object) $user;

        return $next($request);
    }
}